package me.keiwu.log.service.impl;

import com.alibaba.fastjson.JSON;
import me.keiwu.log.dao.LogDonateStepDao;
import me.keiwu.log.domain.LogDonateStep;
import me.keiwu.log.rpc.UserRpc;
import me.keiwu.log.service.LogDonateService;
import me.keiwu.pub.data.service.UserInfoBean;
import me.keiwu.pub.util.CacheUtil;
import me.keiwu.pub.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by kei on 18/12/2017.
 */
@Service
public class LogDonateServiceImpl implements LogDonateService {

    @Autowired
    private LogDonateStepDao logDonateStepDao;
    @Autowired
    private UserRpc userRpc;
    @Autowired
    private CacheUtil cacheUtil;



    @Override
    public void logDonateStep(Long userId, Integer donateStep, Integer logTime) {
        LogDonateStep log = new LogDonateStep();
        log.setUserId(userId);
        log.setDonateStep(donateStep);
        UserInfoBean info = JSON.parseObject(userRpc.userInfoCache(userId), UserInfoBean.class);
        log.setAvatar(info.getWxAvatarUrl());
        log.setNickName(info.getNickName());
        log.setGender(info.getGender());
        log.setCreatedTime(DateUtil.getUnixTime());
        log.setLogTime(logTime);
        logDonateStepDao.save(log);
    }

    @Override
    public void repairFromDB(int from, int to) {
        List<LogDonateStep> steps = logDonateStepDao.findByCreatedTimeFromTo(from, to);
        List<Long> userIdList = new ArrayList<>();
        // 暂时需要手动清零
        for (LogDonateStep step : steps) {
            // 当前个人缓存步数
            int userStep = cacheUtil.getUserDonateSteps(step.getUserId());
            // 增加总步数
            cacheUtil.incrTotalDonateSteps(step.getDonateStep());
            // 更新个人缓存步数
            cacheUtil.setUserDonateSteps(step.getUserId(), userStep + step.getDonateStep());
            if (userIdList.contains(step.getUserId())) continue;
            // 新来的，增加总人数
            cacheUtil.incrTotalDonateUsers();
            userIdList.add(step.getUserId());
        }

    }

    @Override
    public List<LogDonateStep> getTopNLog(Integer n) {
        return logDonateStepDao.getTopN(n);
    }


}
